using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL_UPCTableAdapters;
using upcNameSpace;

/// <summary>
/// Summary description for BL_UPC
/// </summary>
namespace BusinessLayer
{
    public class BL_UPC
    {
        inventoryTableAdapter InvTA = new inventoryTableAdapter();
        tagsTableAdapter tagsTA = new tagsTableAdapter();
        inv_typeTableAdapter TypeTA = new inv_typeTableAdapter();
        necessityTableAdapter necTA = new necessityTableAdapter();
        upc_taggedTableAdapter utTA = new upc_taggedTableAdapter();
        inventory inv = new inventory();
        
        DateTime NOW = DateTime.Now;
        
        upc UPC = new upc();
        
        public BL_UPC()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        
        //Booleans
        public bool IsInInventory(string upc)
        {
            int result;
            result = Convert.ToInt16(InvTA.UPCCount(upc));
            if (result > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        public bool IsValidUPC(string upc)
        {
            structLookupEAN UPCSearchResults = UPC.retrieveUPCInfo(upc);
            if (UPCSearchResults.found)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsUniqueItemType(string type)
        {
            int res = Convert.ToInt32(TypeTA.isUnique(type));
            if (res > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        //Business Functions
        public structLookupEAN ProcessScanIn(string inupc)
        {
            structLookupEAN result = new structLookupEAN();
            DAL_UPC.inventoryDataTable dt = new DAL_UPC.inventoryDataTable();
            
            if (!IsValidUPC(inupc))
            {
                result.found = false;
                result.description = "UPC Does Not Exist";
                return result;
            }
            result = UPC.retrieveUPCInfo(inupc);

            if (!IsInInventory(result.upc))
            {
                result.isInventory = false;
                InvTA.InsertQuery(result.upc, 1, NOW, 1, Convert.ToDouble(0.00));
            }
            else
            {
                result.isInventory = true;
                dt = InvTA.GetDataByUPC(result.upc);
                foreach (DAL_UPC.inventoryRow Row in dt)
                {
                    InvTA.UpdateUPC(Convert.ToInt16(Row.instock + 1),NOW,Convert.ToInt16(Row.specification),Convert.ToDouble(Row.lastprice),result.upc);
                }
            }
            return result;
        }

        public structLookupEAN ProcessScanOut(string outupc)
        {
            structLookupEAN result = new structLookupEAN();
            DAL_UPC.inventoryDataTable dt = new DAL_UPC.inventoryDataTable();

            if (!IsValidUPC(outupc))
            {
                result.found = false;
                result.description = "UPC Does Not Exist";
                return result;
            }

            result = UPC.retrieveUPCInfo(outupc);
            if (!IsInInventory(result.upc))
            {
                result.isInventory = false;
                InvTA.InsertQuery(result.upc, 0, NOW, 1, Convert.ToDouble(0.00));
            }

            else
            {
                result.isInventory = true;
                dt = InvTA.GetDataByUPC(result.upc);
                foreach (DAL_UPC.inventoryRow Row in dt)
                {
                    if (Row.instock > 0)
                    {
                        InvTA.UpdateUPC(Convert.ToInt16(Row.instock - 1), NOW, Convert.ToInt16(Row.specification), Convert.ToDouble(Row.lastprice), result.upc);
                    }
                }
            }
            return result;
        }

        public void UpdateUPC(string upc, int instock, int item, DateTime dteLastPurch, double price)
        {
            DAL_UPC.inventoryDataTable dt = new DAL_UPC.inventoryDataTable();
            dt = InvTA.GetDataByUPC(upc);

            instock = instock + Convert.ToInt32(dt.Rows[0].ItemArray[2]);

            if (dteLastPurch.Year == 1900)
            {
                dteLastPurch = Convert.ToDateTime(dt.Rows[0].ItemArray[3]);
            }
            
            if (item < 1)
            {
                item = Convert.ToInt32(dt.Rows[0].ItemArray[4]);
            }

            if (price < 0.01)
            {
                price = Convert.ToDouble(dt.Rows[0].ItemArray[5]);
            }
            
            foreach (DAL_UPC.inventoryRow Row in dt)
            {
                InvTA.UpdateUPC(instock, dteLastPurch, item, price, upc);
            }
        }

        public void UpdateUPC(InventoryStructure Inv)
        {
            DAL_UPC.inventoryDataTable dt = new DAL_UPC.inventoryDataTable();
            int nec;
            dt = InvTA.GetDataByUPC(Inv.upc);
            foreach (DAL_UPC.inventoryRow Row in dt)
            {
                InvTA.UpdateUPC(Inv.instock, Row.dteLastPuchased, Inv.itemType, Convert.ToDouble(Inv.lastPrice), Inv.upc);
            }
        }

        public void UpdateItemType(TypeStructure Type)
        {
            TypeTA.UpdateType(Type.index, Type.type, Type.description, Type.index);
        }

        public void AddItemType(string type, string description)
        {                           
               TypeTA.InsertQuery(type, description);
        }

        public void DeleteItemType(int index)
        {
            TypeTA.DeleteItemType(index);
        }

        public void AddTag(string tag)
        {
            int Count;
            Count = Convert.ToInt32(tagsTA.doesExist(tag));
            if (Count < 1)
            {
                tagsTA.InsertTag(tag);
            }
        }

        public void AttachTag(string tag, string upc)
        {
            utTA.InsertUPCTag(Convert.ToInt32(tagsTA.GetIdxByName(tag)), Convert.ToInt32(InvTA.GetIdxByUPC(upc)));
        }

        public void deleteTag(string tag)
        {
            tagsTA.DeleteTag(tag);
        }

        public void addNecessity(string upc, int threshhold)
        {
            string strInsert = "";
            DAL_UPC._upc_taggedDataTable dt = new DAL_UPC._upc_taggedDataTable();
            dt = utTA.GetDataByUPC(Convert.ToInt32(InvTA.GetIdxByUPC(upc)));

            foreach (DAL_UPC._upc_taggedRow row in dt)
            {
                strInsert = strInsert + row.tag_idx + ",";
            }

            strInsert = strInsert.Substring(0, strInsert.Length - 1);

            necTA.InsertNecessity(strInsert, threshhold);
        }

        public string GenerateGroceryList(string format)  
        {
            string retchar;
            string tabchar;
            string tableOpen = "";
            string tableClose = "";
            string rowStart = "";
            string rowStop = "";
            string tdStart = "";
            string tdEnd = "";
            string invThresh = "";
            string CurrInv = "";

            if (format == "html")
            {
                retchar = "<br />";
                tabchar = "";
                tableOpen = "<table style='width: 100%'>";
                rowStart = "<tr>";
                rowStop = "</tr>";
                tdStart = "<td style='width: 32%'>";
                tdEnd = "</td>";
                tableClose = "</table>";
            }
            else
            {
                retchar = "\n";
                tabchar = "\t";
                invThresh = "  Inventory Threshhold:  ";
                CurrInv = "  Current Inventory:  ";
            }
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            DateTime Dte = DateTime.Now;
            sb.Append("Grocery List for:  " + Dte.ToString() + retchar + retchar + tableOpen);
            if (format == "html")
            {
                sb.Append(rowStart + tdStart + "Tag" + tdEnd + tdStart + "Inventory Threshold" + tdEnd + tdStart + "Current Inventory" + tdEnd + rowStop);
            }
            DAL_UPC.necessityDataTable outerloopdt = necTA.GetData();
            foreach (DAL_UPC.necessityRow row in outerloopdt)
            {
                string[] rowArray = row.tags.ToString().Split(Convert.ToChar(","));
                DAL_UPC.tagsDataTable innerloopdt = new DAL_UPC.tagsDataTable();
                foreach (string value in rowArray)
                {
                    DAL_UPC.tagsDataTable innerloop = tagsTA.GetDataByTagSet(value);
                    innerloopdt.ImportRow(innerloop.Rows[innerloop.Rows.Count - 1]);
                }
                string Tagset = "";
                foreach (DAL_UPC.tagsRow innerrow in innerloopdt)
                {
                    Tagset = Tagset + "->" + innerrow.tags_name;
                }
                if (Convert.ToInt32(row.inventoryRequired) > Convert.ToInt32(inv.GetInventory(row.tags, rowArray.Length)))
                {
                    sb.Append(rowStart + tdStart + tabchar + Tagset + tdEnd + tdStart + invThresh + row.inventoryRequired.ToString() + tdEnd + tdStart + CurrInv + inv.GetInventory(row.tags, rowArray.Length) + tdEnd + rowStop);
                    if (format != "html")
                    {
                        sb.Append(retchar + retchar);
                    }
                }
            }
            if (format == "html")
            {
                sb.Append(tableClose);
            }

            return sb.ToString();
        }

        public string RetrieveTagList(string upc)
        {
            return inv.GetTagSetByUPC(upc);
        }
        //Data Functions

        public DataSet PopulateItemGroup()
        {
            DAL_UPC.inv_typeDataTable dt = TypeTA.GetData();
            DataSet ds = new DataSet();
            ds.Tables.Clear();
            ds.Tables.Add(dt);
            return ds;
        }

        public DataSet PopulateInventory(int type)
        {
            DAL_UPC.inventoryDataTable dt = InvTA.GetDataByType(type);
            
            DataSet ds = new DataSet();
            ds.Tables.Clear();
            ds.Tables.Add(dt);
            return ds;
        }

        public TypeStructure RetrieveSpecificType(int ItemTypeIndex)
        {
            TypeStructure Type = new TypeStructure();
            DAL_UPC.inv_typeDataTable dt = TypeTA.GetTypeByIdx(ItemTypeIndex);
            foreach (DAL_UPC.inv_typeRow row in dt)
            {
                Type.type = row.type;
                Type.description = row.descr;
                Type.index = Convert.ToInt32(row.type_idx);
            }
            return Type;
        }

        public structLookupEAN RetrieveUPC(string upc)
        {
            return UPC.retrieveUPCInfo(upc);
        }

        public int RetrieveInventory(string upc)
        {
            DAL_UPC.inventoryDataTable dt = InvTA.GetDataByUPC(upc);
            foreach (DAL_UPC.inventoryRow Row in dt)
            {
                return Convert.ToInt32(Row.instock);
            }
            return (0);
        }

        //Public Structures
        public struct TypeStructure
        {
            public string type;
            public string description;
            public int index;
        }

        public struct ItemStructure
        {
            public string itemname;
            public string description;
            public int index;
            public int itemtype;
            public bool necessary;
        }

        public struct InventoryStructure
        {
            public string upc;
            public DateTime date;
            public int instock;
            public int itemType;
            public double lastPrice;
        }
    }
}